package cn.iotnc.camera.util

import android.os.Looper
import android.view.View
import androidx.annotation.CheckResult
import androidx.annotation.RestrictTo
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.filter

private var <T : View> T.triggerLastTime: Long
    set(value) = setTag(1766613352, value)
    get() = getTag(1766613352) as? Long ?: 0L

fun <T : View> T.clickEnable(delay: Long = 800L): Boolean {
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime > delay) {
        triggerLastTime = currentClickTime
        return true
    }
    return false
}

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun checkMainThread() = check(Looper.myLooper() == Looper.getMainLooper()) {
    "Expected to be called on the main thread but was " + Thread.currentThread().name
}

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun View.clicks(delay: Long = 800L): Flow<View> = callbackFlow<View> {
    checkMainThread()
    val listener = View.OnClickListener {
        safeOffer(it)
    }
    setOnClickListener(listener)
    awaitClose { setOnClickListener(null) }
}.conflate().filter { it.clickEnable(delay) }